import {
  queryCurrent,
  queryByUserId,
  queryActions
} from './service';

const Model = {
  namespace: 'userCenter',
  state: {
    currentUser: {},
    list: [],
    likes: [],
    stars: []
  },
  effects: {
    *fetchCurrent(_, { call, put }) {
      const res = yield call(queryCurrent);
      const user = res.data;
      let tags = [];
      if (user.tags != null && user.tags != ''){
        let temp = user.tags.split(',');
        temp.map((item, index) => {
          tags.push({
            key: index + '',
            label: item
          })
        })
      }
      user.tags = tags;
      yield put({
        type: 'saveCurrentUser',
        payload: user,
      });
      return user;
    },

    *fetchByUser({ payload }, { call, put }) {
      const res = yield call(queryByUserId, payload);
      yield put({
        type: 'queryList',
        payload: Array.isArray(res.data) ? res.data : [],
      });
    },

    *fetchLikes({ payload }, { call, put }) {
      const res = yield call(queryActions, payload);
      yield put({
        type: 'queryLikes',
        payload: res.data,
      });
    },

    *fetchStars({ payload }, { call, put }) {
      const res = yield call(queryActions, payload);
      yield put({
        type: 'queryStars',
        payload: res.data,
      });
    }
  },
  reducers: {
    saveCurrentUser(state, action) {
      return { ...state, currentUser: action.payload || {} };
    },

    queryList(state, action) {
      return { ...state, list: action.payload };
    },

    queryLikes(state, action) {
      return { ...state, likes: action.payload };
    },

    queryStars(state, action) {
      return { ...state, stars: action.payload };
    },
  },
};
export default Model;
